﻿using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Org.BouncyCastle.Asn1.X509;
using System.Diagnostics.Metrics;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace worktop;

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private string path = "";
    public MainWindow()
    {
        InitializeComponent();
    }

    private IWorkbook GetExcel()
    {
        var openFileDialog = new Microsoft.Win32.OpenFileDialog()
        {
            //Filter = "路线文档 (.rfa)|*.rfa",
            Multiselect = false
        };
        bool? result = openFileDialog.ShowDialog();
        if (result == true)
        {
            string[] fileNames = openFileDialog.FileNames;
            foreach (string item in fileNames)
            {
                path = item;
            }
        }

        IWorkbook workbook = WorkbookFactory.Create(path);

        return workbook;
    }
    #region 合并sheet工具
    private void Btn_Mergesheet_Click(object sender, RoutedEventArgs e)
    {
        IWorkbook workbook = GetExcel();

        Lable_Mergesheet_FilePath.Content = path;
        int sheetcount = workbook.NumberOfSheets;
        if (sheetcount <= 1)
        {
            return;
        }
        
        ISheet sheet0 = workbook.GetSheetAt(0);
        int newline = sheet0.LastRowNum;
        for (int i = 1; i < sheetcount; i++)
        {
            ISheet sheet = workbook.GetSheetAt(i);
            for (int j = 1; j < sheet.LastRowNum; j++)
            {
                newline++;
                IRow row = sheet0.CreateRow(newline);
                IRow old = sheet.GetRow(j);
                for (int k = 0; k < old.LastCellNum; k++)
                {
                    row.CreateCell(k).SetCellValue(old.GetCell(k).ToString());
                }
            }
        }
        
        FileStream file = new FileStream(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
        workbook.Write(file, true);
        file.Close();
        
        workbook.Close();

        MessageBox.Show("Done");
    }
    #endregion
}